import { pathToRegexp } from 'path-to-regexp';
import type { Route } from '@ant-design/pro-layout/lib/typings';

/**
 * route path值与uri是否匹配
 * @param routePath route path值
 * @param uri uri地址
 */
export function routePathMatchUri(routePath: string, uri: string): boolean {
  if (routePath === uri) {
    return true;
  }
  const re = pathToRegexp(routePath);
  const result = re.exec(uri);
  return result !== null && result.length > 0;
}

/**
 * 判断路由集合中是否有与当前uri匹配的path
 * @param routes 路由集合
 * @param uri uri地址
 */
export function hasMatch(routes: Route[], uri: string): boolean {
  let matched = false;
  for (let idx = 0; idx < routes.length; idx += 1) {
    const localRoute = routes[idx];
    if (localRoute !== null && localRoute.path) {
      matched = routePathMatchUri(localRoute.path, uri);
      if (matched) {
        return matched;
      }
      if (localRoute.routes && localRoute.routes.length > 0) {
        matched = hasMatch(localRoute.routes, uri);
        if (matched) {
          return matched;
        }
      }
    }
  }
  return matched;
}

/**
 * 根据uri获取第一个匹配到的路由
 * @param routes 路由集合
 * @param uri uri地址
 */
export function routeMatched(routes: Route[], uri: string): Route | null {
  let route = null;
  for (let idx = 0; idx < routes.length; idx += 1) {
    const localRoute = routes[idx];
    if (localRoute !== null && localRoute.path) {
      if (routePathMatchUri(localRoute.path, uri)) {
        route = localRoute;
      }
      if (route) {
        return route;
      }
      if (localRoute.routes && localRoute.routes.length > 0) {
        route = routeMatched(localRoute.routes, uri);
        if (route) {
          return route;
        }
      }
    }
  }
  return route;
}
